<template>
  <div class="app-container">
    <el-row style="margin-bottom:10px">
      <el-col :span="4">
        <el-input v-model="search.keyword" placeholder="Keyword" style="width:95%" />
      </el-col>
      <el-button type="primary" @click="getRoles">Search</el-button>
      <el-button type="primary" @click="handleAddRole">Add</el-button>
    </el-row>
    <el-table
      :data="rolesList"
      style="width: 100%;margin-top:30px"
      border
      :empty-text="empty_text"
    >
      <el-table-column align="center" prop="id" label="ID" width="70">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center" label="Template Name" width="250">
        <template slot-scope="scope">{{ scope.row.template_name }}</template>
      </el-table-column>
      <el-table-column align="center" label="Template Type" width="180">
        <template slot-scope="scope">{{ scope.row.template_type_name }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Photo" width="80">
        <template slot-scope="scope">
          <el-checkbox :value="scope.row.photo_flag===1" />
        </template>
        <!-- <template slot-scope="scope">{{ scope.row.photo_flag }}</template> -->
      </el-table-column>
      <el-table-column align="header-center" label="Options">
        <template slot-scope="scope">{{ scope.row.content.join(',') }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Default Template" width="140">
        <template slot-scope="scope">
          <el-checkbox :value="scope.row.is_default===1" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="Action" width="80">
        <template slot-scope="scope">
          <el-col :span="12">
            <el-link style="font-size:18px;" class="el-icon-edit icon-class" @click="handleEdit(scope)" />
          </el-col>
          <el-col :span="12">
            <el-link style="font-size:18px;" class="el-icon-delete icon-class" @click="Deleteinfo(scope)" />
          </el-col>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? 'Edit Template' : 'New Template'"
    >
      <div style="margin:0 30px">
        <el-form ref="connectForm" :rules="rules" :model="role" label-width="150px" label-position="left">
          <el-form-item label="Template Name" prop="template_name">
            <el-input v-model="role.template_name" placeholder="Template Name" />
          </el-form-item>
          <el-form-item label="Photo">
            <el-checkbox v-model="checked" />
          </el-form-item>
          <el-form-item label="Template Type" prop="template_type">
            <el-select v-model="role.template_type" placeholder="Please Choose" no-data-text="Can't find record" @change="selectworkName">
              <el-option
                v-for="item in wi_template_type"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
            <!-- <el-input v-model="role.template_type" placeholder="template_type" /> -->
          </el-form-item>
          <el-form-item v-if="role.template_type === 3" label="Default Template">
            <el-checkbox v-model="role.is_default" />
          </el-form-item>
        </el-form>
        <div v-if="play">
          <section>
            <my-test
              v-for="(item, index) in contents"
              :key="index"
              :index="index"
              :item-c="item"
            />
          </section>
          <el-button style="margin-left:150px" size="mini" icon="el-icon-circle-plus" @click="add" />
        </div>
        <div style="text-align:right">
          <el-button type="danger" @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirmRole">Confirm</el-button>
        </div>
      </div>
    </el-dialog>

    <el-pagination
      style="margin-top:10px;float:right"
      background
      layout="prev,pager,next"
      :total="totalpage"
      :current-page="search.page"
      :page-size="search.per_page"
      @current-change="handleIndexChange"
    />
  </div>
</template>

<script>
import { baseAPI } from '@/utils/request'
import MyTest from './Contents.vue'
import { getwitemplate, savewitemplate, deletewitemplate, gettemplatetype, getwitemplatedetail } from '@/api/Instruction/template/index'

const defaultRole = {
  id: 0,
  name: '',
  remark: '',
  routes: []
}

export default {
  components: {
    MyTest
  },
  data() {
    return {
      role: {
        id: '',
        template_name: '',
        photo_flag: '',
        content: [],
        template_type: '',
        is_default: false,
        defaultTemplate: false
      },
      contents: [{
        content: ''
      }],
      search: {
        keyword: '',
        page: 1,
        per_page: 10
      },
      wi_template_type: [{
        value: '',
        name: ''
      }],
      empty_text: '',
      checked: true,
      play: false,
      totalpage: 0,
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      rules: {
        template_name: [{ required: true, message: 'Please Enter Template Name', trigger: 'blur'
        }],
        template_type: [{ required: true, message: 'Please Choose Template Type', trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  watch: {
    dialogVisible(newValue, oldValue) {
      if (this.$refs['connectForm']) this.$refs['connectForm'].clearValidate()
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getRoutes()
    this.getRoles()
    this.gettemplatetypes()
  },
  methods: {
    add() {
      this.contents.push({
        content: ''
      })
    },
    handleIndexChange(index) {
      this.search.page = index
      this.getRoles()
    },
    async getRoutes() {
      const res = await baseAPI.get('user/role/routes')
      this.serviceRoutes = res
      this.routes = res
    },
    async gettemplatetypes() {
      const res = await gettemplatetype({ dict_type: 'wi_template_type' })
      this.wi_template_type = res
    },
    async getRoles() {
      this.empty_text = 'Loading ......'
      await getwitemplate(this.search).then(res => {
        this.rolesList = res.data
        this.totalpage = res.total
        this.search.per_page = parseInt(res.per_page)
        this.search.page = parseInt(res.current_page)
        this.empty_text = 'Can\'t find record in table'
      }).catch(() => {
        this.rolesList = []
        this.empty_text = 'Can\'t find record in table'
      })
    },
    handleAddRole() {
      this.play = false
      this.contents.splice(this.contents)
      this.role = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
      this.checked = false
    },
    async handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.role = await getwitemplatedetail({ id: scope.row.id })
      this.role.is_default = this.role.is_default === 1
      if (this.role.photo_flag === 1) {
        this.checked = true
      } else {
        this.checked = false
      }
      this.selectworkName(this.role.template_type)
      this.contents.splice(this.contents)
      for (var i = 0; i < this.role.content.length; i++) {
        this.contents.push({ content: this.role.content[i] })
      }
    },
    selectworkName(value) {
      let obj = {}
      obj = this.wi_template_type.find((item) => {
        return item.value === value
      })
      if (obj.name === 'Dropdown') {
        this.contents.push({ content: '' })
        this.play = true
      } else {
        this.contents.splice(this.contents)
        this.play = false
      }
    },
    Deleteinfo({ $index, row }) {
      this.$confirm('Confirm to remove the Template?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      })
        .then(async() => {
          await deletewitemplate({ id: row.id })
          this.getRoles()
          this.$message({
            type: 'success',
            message: 'Delete succed!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    async confirmRole() {
      this.$refs.connectForm.validate(async valid => {
        if (valid) {
          if (this.checked) {
            this.role.photo_flag = '1'
          } else {
            this.role.photo_flag = '0'
          }
          this.role.content = this.contents.map(function(v) { return v.content })
          await savewitemplate(this.role)
          this.dialogVisible = false
          this.getRoles()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
